package com.mischa.doedeljas.server;

import java.util.Vector;

import com.mischa.doedeljas.Card;
import com.mischa.doedeljas.Card.Suit;
import com.mischa.doedeljas.Deck;

public class Game 
{
	private int _gameId;
	
	private Player[] _players = new Player[3];
	private int _dealer;
	
	private Suit _trumpSuit = null;
	private Vector<Trick> _completedTricks = new Vector<Trick>();
	private Trick _currentTrick = null;

	public Game(int gameId) 
	{
		_gameId = gameId;
		_dealer = -1;
	}
	
	public int getGameId() {
		return _gameId;
	}

	public boolean addPlayer(Player player) 
	{
		for (int i = 0; i < 3; ++i)
		{
			if (_players[i] == null)
			{
				_players[i] = player;
				player.joined(this, i);
				dealCardsWhenAllPlayersPresent();
				return true;
			}
		}
		
		return false;
	}

	private void dealCardsWhenAllPlayersPresent() {
		for (int i = 0; i < 3; ++i)
		{
			if (_players[i] == null)
			{
				return;
			}
		}

		_dealer = (_dealer + 1) % 3;
		
		Deck deck = new Deck();
		
		for (int player = 0; player < 3; ++player)
		{
			int numberOfCardsToDeal = (player == _dealer ? 12 : 10);
			Vector<Card> hand = new Vector<Card>();
			
			for (int cards = 0; cards < numberOfCardsToDeal; ++cards)
			{				
				hand.add(deck.dealCard());
			}
			
			_players[player].deal(hand);
		}
		
		_players[_dealer].youAreDealer();
		
		_currentTrick = new Trick(_trumpSuit, _dealer);
		
		for (int player = 0; player < 3; ++player)
		{
			_players[player].trickStatus(_currentTrick);
		}
	}

	public void playCard(Card card, Player playedBy) {		
		if (playedBy.getPlayerId() == _currentTrick.getNextPlayer() && playedBy.holdsCard(card))
		{			
			_currentTrick.play(card);
			
			for (int player = 0; player < 3; ++player)
			{
				_players[player].trickStatus(_currentTrick);
			}
			
			if (_currentTrick.isComplete())
			{
				_completedTricks.add(_currentTrick);
				if(_completedTricks.size() == 10)
				{
					_dealer = (_dealer + 1) % 3;
					dealCardsWhenAllPlayersPresent();
				}
				else
				{
					_currentTrick = new Trick(_trumpSuit, _currentTrick.getNextPlayer());
				}
			}
		}
	}

	public void setTrump(Suit suit) {
		_trumpSuit = suit;
		
		for (int player = 0; player < 3; ++player)
		{
			_players[player].trumpChosen(suit);
		}
	}

	public int getDealer() {		
		return _dealer;
	}
}
